<template>
  <div id="addQuestionView">
    <h2>{{ `${flag ? "创建题目" : "更新题目"}` }}</h2>
    <a-form :model="form">
      <a-form-item field="title" label="题目标题">
        <a-input v-model="form.title" placeholder="请输入题目标题" />
      </a-form-item>
      <a-form-item field="tags" label="题目标签">
        <a-input-tag v-model="form.tags" placeholder="请选择或输入标签" allow-clear />
      </a-form-item>
      <a-form-item field="content" label="题目内容">
        <MDEditor :value="form.content" :handle-change="onContentChange" />
      </a-form-item>
      <a-form-item field="answer" label="答案">
        <MDEditor :value="form.answer" :handle-change="onAnswerChange" />
      </a-form-item>
      <a-form-item label="题目配置" :content-flex="false" :merge-props="false">
        <a-space direction="vertical" style="min-width: 485px">
          <a-form-item field="judgeConfig.timeLimit" label="时间限制(ms)">
            <a-input-number
              v-model="form.judgeConfig.timeLimit"
              placeholder="请输入时间限制"
              size="large"
              mode="button"
              min="0"
            />
          </a-form-item>
          <a-form-item field="judgeConfig.memoryLimit" label="内存限制(kb)">
            <a-input-number
              v-model="form.judgeConfig.memoryLimit"
              placeholder="请输入内存限制"
              size="large"
              mode="button"
              min="0"
            />
          </a-form-item>
          <a-form-item field="judgeConfig.stackLimit" label="堆栈限制(kb)">
            <a-input-number
              v-model="form.judgeConfig.stackLimit"
              placeholder="请堆栈时间限制"
              size="large"
              mode="button"
              min="0"
            />
          </a-form-item>
        </a-space>
      </a-form-item>
      <a-form-item label="用例配置" :content-flex="false" :merge-props="false">
        <a-form-item v-for="(judgeCaseItem,index) of form.judgeCase"
                     :key="index"
                     no-style
        >
          <a-space direction="vertical" style="min-width: 440px">
            <a-form-item :field="`from.judgeCase[${index}].input`" :label="`输入用例-${index}`"
                         :key="index">
              <a-input v-model="judgeCaseItem.input" placeholder="输入测试用例" />
            </a-form-item>
            <a-form-item :field="`from.judgeCase[${index}].output`" :label="`输出用例-${index}`"
                         :key="index">
              <a-input v-model="judgeCaseItem.output" placeholder="输出测试用例" />
            </a-form-item>
            <a-button @click="handleDelete(index)" status="danger">Delete</a-button>
          </a-space>
        </a-form-item>
      </a-form-item>
      <a-form-item>
        <div style="margin-top: 16px">
          <a-button @click="handleAdd" type="outline" status="success">增加测试用例</a-button>
        </div>
      </a-form-item>
      <a-form-item>
        <div style="margin-top: 16px" />
        <a-button type="primary" style="min-width: 240px" @click="onSubmit">提交</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, toRaw } from "vue";
import MDEditor from "@/components/MDEditor.vue";
import { QuestionControllerService } from "../../../generated";
import message from "@arco-design/web-vue/es/message";
import { useRoute } from "vue-router";
import { findDomNode } from "@arco-design/web-vue/es/_utils/dom";

const form = ref({
  "title": "",
  "answer": "",
  "content": "",
  "tags": [],
  "judgeConfig": {
    "timeLimit": 1000,
    "memoryLimit": 1000,
    "stackLimit": 1000
  },
  "judgeCase": [
    {
      "output": "",
      "input": ""
    }
  ]
});
const route = useRoute();
const updatePage = route.path.includes("update");
const flag = ref(false);

/**
 * 根据ID获取题目信息
 */
const getQuestionById = async () => {
  const questionId = route.query.id;
  if (!questionId) {
    return;
  }
  const result = await QuestionControllerService.getQuestionByIdUsingGet(questionId as any);
  if (result.code === 0) {
    form.value = checkQuestionNullAttr(result.data as any);
  } else {
    message.error("查询需要更新的题目信息失败," + result.message + "!");
  }
};

/**
 * 检查查询的题目信息属性为空就赋予默认值,不为空就做JSON字符串转换为对象
 * @param question
 */
const checkQuestionNullAttr = (question: any) => {
  if (!question.judgeCase) {
    question.judgeCase = [
      {
        "output": "",
        "input": ""
      }
    ];
  } else {
    question.judgeCase = JSON.parse(question.judgeCase as any);
  }
  if (!question.judgeConfig) {
    form.value.judgeConfig = {
      "timeLimit": 1000,
      "memoryLimit": 1000,
      "stackLimit": 1000
    };
  } else {
    question.judgeConfig = JSON.parse(question.judgeConfig as any);
  }

  if (!question.tags) {
    question.value.tags = [];
  } else {
    question.tags = JSON.parse(question.tags as any);
  }
  return question;
};

/**
 * 挂载事件
 */
onMounted(() => {
  if (updatePage) {
    flag.value = false;
  } else {
    flag.value = true;
  }
  getQuestionById();
});

/**
 * 更新或者创建题目信息
 */
const onSubmit = async () => {
  if (updatePage) {
    const result = await QuestionControllerService.updateQuestionUsingPost(form.value);
    if (result.code === 0) {
      await getQuestionById();
      message.success("更新题目成功!");
    } else {
      message.error("更新题目失败," + result.message);
    }
  } else {
    const result = await QuestionControllerService.addQuestionUsingPost(form.value);
    if (result.code === 0) {
      message.success("创建题目成功!");
    } else {
      message.error("创建题目失败," + result.message);
    }
  }
};

/**
 * 答案文本编辑器值实时更新
 * @param newContent
 */
const onAnswerChange = (newContent: string) => {
  form.value.content = newContent;
};

/**
 * 题目内容文本编辑器值实时更新
 * @param newAnswer
 */
const onContentChange = (newAnswer: string) => {
  form.value.content = newAnswer;
};

/**
 * 增加测试输入输出用例
 */
const handleAdd = () => {
  form.value.judgeCase.push({
    input: "",
    output: ""
  });
};

/**
 * 删除测试输入输出用例
 */
const handleDelete = (index: number) => {
  form.value.judgeCase.splice(index, 1);
};
</script>

<style scoped>
#addQuestionView {
}
</style>
